package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.core.model.Admin;
import com.geyue.core.model.Gift;
import com.geyue.core.service.GiftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Lyon on 2017/6/2.
 */
@Controller
@RequestMapping("/gift")
public class GiftController {

    @Autowired
    private GiftService giftService;

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String list(HttpSession session, Model model){
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return "error";

        return "gift/list";
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ResponseBody
    public Res index(Gift gift, Integer pageSize, Integer pageNum, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return Res.fail("登录信息过时,请重新登录!");

        return Res.success("", giftService.getPage(pageNum, pageSize, gift));
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return "error";

        return "gift/add";
    }

    @RequestMapping(value = "/",method = RequestMethod.POST)
    @ResponseBody
    public Res add(Gift gift, HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return Res.fail("登录信息过期,重新登录!");

        if(giftService.saveNotEmpty(gift) > 0)
            return Res.success("添加成功!");

        return Res.fail("添加失败!");
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public Res del(@PathVariable Integer id, HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return Res.fail("登录信息过期,重新登录!");

        if(giftService.deleteByKey(id) > 0)
            return Res.success("删除成功!");

        return Res.fail("删除失败!");
    }
}
